<template>
  <SlideViewSingle v-if="id && visible"
                   :body-style="{padding: 0, height: '100%'}"
                   class="d-view"
                   @afterEnter="viewAfterEnter"
                   @close="hideView">
    <div v-loading="crmOption.loading" ref="crmDetailMain" class="detail-main">
      <flexbox v-if="canShowDetail && detailData" direction="column"
               align="stretch" class="d-container">
        <SzDetailHeadSingle
            :detail="detailData"
            :head-details="headDetails"
            :id="id"
            :crm-type="crmOption.crmType"
            :page-list="pageList"
            @pageChange="pageChange"
            @handle="detailHeadHandle"
            @close="hideView"/>
        <flexbox class="d-container-bd" align="stretch">
          <el-tabs v-model="currentTabName" type="border-card" class="d-container-bd--left">
            <el-tab-pane v-for="(item, index) in tabNames" :key="index"
                         :label="item.label" :name="item.name" lazy>
              <CRMEditBaseInfo v-if="item.name === 'CRMEditBaseInfo'"
                               :is="item.name"
                               :detail="detailData"
                               :id="id"
                               :crm-type="crmOption.crmType"
                               :ignore-fields="['status']"
                               @handle="detailHeadHandle">
                <sections title="图片信息" class="b-cells" content-height="auto">
                  <div class="image">
                    <div v-if="mainFileList.length > 0" class="image-info">
                      <div class="image-info__label">产品图片</div>
                      <div class="image-info__list">
                        <img v-src="item.url"
                             v-for="(item, index) in mainFileList"
                             :key="index"
                             class="main-img"
                             @click="previewImage(mainFileList, index)">
                      </div>
                    </div>
                    <div v-if="detailFileList.length > 0" class="image-info">
                      <div class="image-info__label">产品详情图片</div>
                      <div class="image-info__list">
                        <img v-src="item.url" v-for="(item, index) in detailFileList"
                             :key="index"
                             class="detial-img"
                             @click="previewImage(detailFileList, index)">
                      </div>
                    </div>
                    <div v-if="detailFileList.length == 0 && mainFileList.length == 0" class="no-img">暂无图片</div>
                  </div>
                </sections>
              </CRMEditBaseInfo>
              <component v-else :is="item.comp"
                         :detail="detailData"
                         :id="id"
                         :crm-type="crmOption.crmType"
                         @handle="detailHeadHandle"/>
            </el-tab-pane>
          </el-tabs>
        </flexbox>
      </flexbox>
    </div>

    <!--        此处是编辑-->
    <ProductCreate v-if="showEditDialog"
                   :action="{type: 'update', id: id, batchId: detailData.batchId, editDetail: detailData}"
                   :crm-type="crmOption.crmType"
                   @save-success="editSaveSuccess"
                   @close="showEditDialog=false"/>
  </SlideViewSingle>
</template>

<script setup>
import CRMEditBaseInfo from '/src/views/crm/componentsNew/BaseInfo/CRMEditBaseInfo.vue' // 产品基本信息
import RelativeFiles from '/src/views/crm/componentsNew/relative/RelativeFiles.vue' // 相关附件
import RelativeHandle from '/src/views/crm/componentsNew/relative/RelativeHandle.vue' // 相关操作
import Sections from '/src/views/crm/componentsNew/Sections.vue'
import {crmOptionKey} from "@/views/crm/componentsNew/SzCrud/keys.js";
import SlideViewSingle from "@/views/crm/componentsNew/SzCrud/SlideView.vue";
import SzDetailHeadSingle from "@/views/crm/componentsNew/SzCrud/detail/SzDetailHead.vue";
import {filedGetInformationAPI} from "@/api/crm/common.js";
import crmTypeModel from "@/views/crm/model/crmTypeModel.js";
import {useSzTab} from "@/views/crm/componentsNew/SzCrud/detail/useSzTab.js";
import {useSzDetail} from "@/views/crm/componentsNew/SzCrud/detail/useSzDetail.js";
import {ElMessage} from "element-plus"
import {crmProductReadAPI} from '/src/api/crm/product.js'
import ProductCreate from "@/views/crm/product/Create.vue";
import {getCurrentInstance} from 'vue'
import {useNumberHook} from "@/hooks/useNumberHook.js";

defineOptions({
  // 客户管理 的 产品详情
  name: 'ProductDetail',
})
const props = defineProps({
  visible: Boolean,
  // 详情信息id
  id: [String, Number],
  // 表示第几个详情
  pageIndex: [String, Number],
  // 用于详情切换
  pageList: Array,
  crmOptionChange: Function
})

const {separator} = useNumberHook();

// 下面的headDetails、tabNames、activityHandle、getDetail需要自定义，不能放在SzDetail中
const headDetails = reactive([
  {title: '产品类别', value: ''},
  {title: '产品单位', value: ''},
  {title: '产品价格', value: ''},
  {title: '产品编码', value: ''}
])

const tabNames = computed(() => {
  return [
    {label: '详细资料', name: 'CRMEditBaseInfo', comp: CRMEditBaseInfo},
    {label: getTabName('附件', tabsNumber.fileCount), name: 'RelativeFiles', comp: RelativeFiles},
    {label: '操作记录', name: 'RelativeHandle', comp: RelativeHandle}
  ]
})

const emits = defineEmits(['update:pageIndex', 'update:visible',
  'crm-detail-update', 'update:id', 'handle', 'crm-tab-num-update', 'hide-view'])

const crmOption = inject(crmOptionKey)
const {currentTabName, tabsNumber, getTabsNum, getTabName}
    = useSzTab(crmOption, toRef(() => props.id))
const {detailData, canShowDetail} = useSzDetail(crmOption)

const detailOption = reactive({
  currentTabName,
  tabsNumber, getTabsNum, getTabName, detailData, canShowDetail
})


currentTabName.value = 'CRMEditBaseInfo'


// 在detail.vue中
watch(() => props.id, () => {
  if (canShowDetail && canShowDetail.value) {
    detailData.value = null
    tabsNumber.value = {}
    getDetail()
    getTabsNum()
  }
})

const mainFileList = computed(() => {
  if (detailData && detailData.mainFileList) {
    return detailData.mainFileList
  }

  return []
})

const detailFileList = computed(() =>  {
  if (detailData && detailData.detailFileList) {
    return detailData.detailFileList
  }

  return []
})

/**
 * 详情
 */
function getDetail() {
  crmOption.loading = true
  crmProductReadAPI({productId: props.id}).then(res => {
    detailData.value = res.data.data

    headDetails[0].value = res.data.data.categoryName
    headDetails[1].value = res.data.data.unit
    headDetails[2].value = separator(res.data.data.price || 0)
    headDetails[3].value = res.data.data.num

    crmOption.loading = false
  }).catch((r) => {
    console.log("r", r)
    crmOption.loading = false
    hideView()
  })
  getBaseInfo()
}

/**
 * 获取基础信息
 */
function getBaseInfo() {
  console.log("getBaseInfo")
  crmOption.loading = true
  filedGetInformationAPI({
    types: crmTypeModel[crmOption.crmType],
    id: props.id
  }).then(res => {
    console.log("filedGetInformationAPI", res.data)
    importList.value = res.data.data
    crmOption.loading = false
  }).catch(() => {
    crmOption.loading = false
  })
}

/**
 * 进入详情页面后的动作
 */
function viewAfterEnter() {
  if (canShowDetail.value) {
    getDetail()
    getTabsNum()
    bus.on('crm-tab-num-update', getTabsNum)
  }
}

/**
 * 关闭
 */
function hideView() {
  emits('hide-view')
}

/**
 * 详情页面切换
 */
function pageChange(type) {
  let currentPageIndex = props.pageIndex
  if (type === 'left') {
    if (props.pageIndex > 0) {
      emits('update:pageIndex', --currentPageIndex)
      emits('update:id', props.pageList[currentPageIndex][`${crmOption.crmType}Id`])
    } else {
      ElMessage.error({message: '没有更多了！'})
    }
  } else {
    if (currentPageIndex < props.pageList.length - 1) {
      emits('update:pageIndex', ++currentPageIndex)
      emits('update:id', props.pageList[currentPageIndex][`${crmOption.crmType}Id`])
    } else {
      ElMessage.error({message: '没有更多了！'})
    }
  }
}


/**
 * 顶部头 操作
 * @param {*} data
 */
function detailHeadHandleClick(data) {
  // if (data.type === 'edit') {
  //   crmOption.createCRMType = 'customer'
  //   createActionInfo.value = {
  //     type: 'update',
  //     id: props.id,
  //     batchId: detailData.value.batchId
  //   }
  //   isCreate.value = true
  //   return false
  // }
}

// 编辑操作
const showEditDialog = ref(false)

/**
 * 顶部头 操作
 * @param {*} data
 */
function detailHeadHandle(data) {
  // 返回值为false 不继续执行
  if (detailHeadHandleClick(data) === false) {
    return
  }

  if (data.type === 'edit') {
    showEditDialog.value = true
    // props.crmOptionChange('isCreate', true)
    // props.crmOptionChange('createShow', true)
  } else if (data.type === 'delete' ||
      data.type === 'exit-team' ||
      data.type === 'alloc' ||
      data.type === 'get' ||
      data.type === 'transfer' ||
      data.type === 'transform' ||
      data.type === 'delete' ||
      data.type === 'put_seas') {
    hideView()
  } else if (data.type === 'state_start' ||
      data.type === 'state_disable' ||
      data.type === 'deal_status' ||
      data.type === 'cancel' ||
      data.type === 'examine') {
    getDetail()
  } else if (data.type === 'save-success') {
    // 但字段编辑成功刷新
    editSaveSuccess()
    return
  }

  emits('handle', data)
}

function editSaveSuccess() {
  emits('crm-detail-update', crmOption.crmType)
  emits('handle', {type: 'save-success'})
  detailOption.detailData = null
  getDetail()
}

const cxt = getCurrentInstance()
const $wkPreviewFile = cxt.appContext.config.globalProperties.$wkPreviewFile

/**
 * 预览图片
 */
function previewImage(list, index) {
  $wkPreviewFile.preview({index: index, data: list})
}
</script>

<style lang="scss" scoped>
.image {
  color: #333;

  &-info {
    margin: 10px 25px 0;

    &__label {
      font-size: 13px;
    }

    &__list {
      overflow-x: auto;
      white-space: nowrap;

      img {
        margin-top: 15px;
        border-radius: $xr-border-radius-base;
        cursor: pointer;
      }

      img + img {
        margin-left: 20px;
      }

      .main-img {
        width: 100px;
        height: 76px;
        object-fit: contain;
        vertical-align: top;
      }

      .detial-img {
        width: 100px;
        height: 80px;
        object-fit: contain;
        vertical-align: top;
      }
    }
  }

  .no-img {
    color: #666;
    margin: 50px 0;
    text-align: center;
  }
}

@import '../styles/crmdetail';
</style>
